package com.kehutong.department.service;

import com.kehutong.common.DoveClient;
import com.kehutong.common.util.Token;
import com.kehutong.department.entity.ThirdDepartment;
import com.kehutong.department.entity.ThirdEmployee;
import com.kehutong.department.entity.ThirdEnterpriseConfig;
import com.kehutong.department.util.DateUtils;
import com.kehutong.department.util.HttpUtils;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.UUIDGenerator;
import org.coraframework.util.secret.MD5;
import org.coraframework.util.time.TimeUtil;

import java.sql.Timestamp;
import java.util.*;

/**
 * TODO
 *
 * @author zhouweipeng
 * @version 1.0
 * @date 2021/9/8 9:56
 */
public class ThridEmployeeService {
    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private DoveClient doveClient;
    /**
     * 中海中台拉取数据
     * @param lastTime 传了则增量、否则全量
     * @return
     */
    private JSONObject pullEmployData(String lastTime,int pageNum,String ext){
        JSONObject extJson=JSONObject.parseObject(ext);
        String url=extJson.getString("url");
        String method="/userApi/v1/synUserInfo";
        String appKey=extJson.getString("appKey");
        String appSecret=extJson.getString("appSecret");
        String timestamp=getTimestamp();
        Map<String,Object>paramMap=new HashMap<String,Object>(); //参数
        Map<String,Object>hearderMap=new HashMap<String,Object>(); //请求头
        if(lastTime!=null){
            paramMap.put("lastTime",lastTime);
        }
        paramMap.put("pageNum",pageNum);
        JSONObject jsonParam = new JSONObject(paramMap);
        JSONObject param=new JSONObject();
        param.put("param",jsonParam);
        String linkString=appKey+"_"+appSecret+"_"+timestamp+"_"+jsonParam.toJSONString();
        hearderMap.put("appKey",appKey);
        hearderMap.put("timestamp",timestamp);
        String sign=MD5.MD5Encode(linkString);
        hearderMap.put("sign",sign);
        String result= HttpUtils.sendByForm(url+method,hearderMap,param);
        if(result!=null){
            return JSONObject.parseObject(result);
        }else{
            return null;
        }
    }
    /**
     * 同步员工数据
     * @return 同步结果
     */
    public void synEmployData(Token token)throws Exception{
        Timestamp start= TimeUtil.timestamp();
        ThirdEnterpriseConfig thirdEnterpriseConfig = jdbcSession.findOne(ThirdEnterpriseConfig.class).eq("companyNo",token.getCompanyNo()).exe();
        Map<String, String>thirdEmployeeMap=getThirdEmployeeMap(token.getCompanyNo());  //企业关系map
        analysisEmployData(1,thirdEnterpriseConfig,thirdEmployeeMap); //解析接口返回、数据入库、同步企微
        thirdEnterpriseConfig.setLastTime(start);//记录拉取时间入库
        jdbcSession.updateById(thirdEnterpriseConfig);
    }

    /**
     * 同步员工数据
     * @return 同步结果
     */
    public void employTask()throws Exception{
        Timestamp start= TimeUtil.timestamp();
        ThirdEnterpriseConfig thirdEnterpriseConfig = jdbcSession.findOne(ThirdEnterpriseConfig.class).eq("code","zhonghai").exe();
        Map<String, String>thirdEmployeeMap=getThirdEmployeeMap(thirdEnterpriseConfig.getCompanyNo());  //企业关系map
        analysisEmployData(1,thirdEnterpriseConfig,thirdEmployeeMap); //解析接口返回、数据入库、同步企微
        thirdEnterpriseConfig.setLastTime(start);//记录拉取时间入库
        jdbcSession.updateById(thirdEnterpriseConfig);
    }

    /**
     * 解析员工信息、从中海的员工同步接口解析、封装成JSONArray返回
     * /userApi/v1/synUserInfo
     * 递归调用、分页调用中海
     * @return
     * @param pageNum  页码
     * @param
     */
    private void analysisEmployData(int pageNum,ThirdEnterpriseConfig thirdEnterpriseConfig,Map<String, String>thirdEmployeeMap)throws Exception{
        JSONObject resultJson=null; //用来存接口调用返回
        if(Objects.nonNull(thirdEnterpriseConfig.getLastTime())){
            String lastTime=DateUtils.timestampToStr(thirdEnterpriseConfig.getLastTime(),DateUtils.PATTERN_1);
            resultJson=pullEmployData(lastTime,pageNum,thirdEnterpriseConfig.getExt());
        }else{
            resultJson=pullEmployData(null,pageNum,thirdEnterpriseConfig.getExt());
        }
        String resultCode=resultJson.getString("resultCode");
        if("0".equals(resultCode)){
            Map<String,ThirdDepartment>thirdDepartmentMap=getThirdDepartmentMap(); //部门
            JSONArray userList=new JSONArray();
            JSONObject dataJson=resultJson.getJSONObject("data");
            int pages=dataJson.getInteger("pages");
            JSONArray array=dataJson.getJSONArray("list");
            for(int i=0,len=array.size();i<len;i++){
                JSONObject employJson=array.getJSONObject(i);
                String guid=employJson.getString("guid"); //用户id
                String userName=employJson.getString("userName"); //用户名
                String fullName=employJson.getString("fullName"); //姓名
                String phoneticAlphabet=employJson.getString("phoneticAlphabet"); //姓名拼音
                String email=employJson.getString("email");
                String gender=employJson.getString("gender"); //性别（1:男，2:女）
                String mobile=employJson.getString("mobile"); //手机
                String seq=employJson.getString("seq");  //排序
                String orgGuid=employJson.getString("orgGuid");  //所属组织唯一编码guid
                ThirdDepartment thirdDepartment=thirdDepartmentMap.get(orgGuid);  //部门的关系
                String disabledStatus=employJson.getString("disabledStatus");  //状态（-1、删除(上游系统删除)，0、禁用，1、启用）
                String deleteStatus=employJson.getString("deleteStatus");  //删除状态（0、删除(中台删除)，1、未删除）
                Date createTime=employJson.getDate("createTime");
                Date updateTime=employJson.getDate("updateTime");
                JSONObject user=new JSONObject();
                user.put("guid",guid);
                if(thirdEmployeeMap.containsKey(guid)){
                    user.put("khtId",thirdEmployeeMap.get("khtId"));
                }
                user.put("userName",userName);
                user.put("fullName",fullName);
                user.put("phoneticAlphabet",phoneticAlphabet);
                user.put("email",email);
                user.put("gender",gender);
                user.put("mobile",mobile);
                user.put("seq",seq);
                user.put("orgGuid",orgGuid);
                user.put("disabledStatus",disabledStatus);
                user.put("deleteStatus",deleteStatus);
                user.put("createTime",createTime);
                user.put("updateTime",updateTime);
                if(thirdDepartment!=null){
                    user.put("khtOrgGuid",thirdDepartment.getKhtId());
                }
                userList.add(user);
            }
            if(userList.size()>0){
                JSONObject params=new JSONObject();
                params.put("userList",userList);
                JSONObject result = doveClient.post("/basic/employee/service/saveThridBatch", (http) -> {
                    http.setBody(params.toJSONString());
                });
                if (result.getIntValue("code") == 200) {
                    // TODO: 2021/9/8  这里入库中间表建立关系
                    JSONArray relationArray=result.getJSONArray("data");
                    for(int j=0,len=relationArray.size();j<len;j++){
                        JSONObject relation=relationArray.getJSONObject(j);
                        ThirdEmployee thirdEmployee= Pool.newInstance(ThirdEmployee.class, UUIDGenerator.randomUUID());
                        thirdEmployee.setCompanyNo(thirdEnterpriseConfig.getCompanyNo());
                        thirdEmployee.setThirdId(relation.getString("thirdId"));
                        thirdEmployee.setKhtId(relation.getString("khtId"));
                        jdbcSession.insert(thirdEmployee);
                    }
                }
                if(pages!=pageNum&&array.size()!=0){
                    pageNum++; //下一页
                    analysisEmployData(pageNum,thirdEnterpriseConfig,thirdEmployeeMap);
                }
            }
        }
    }
    private String getTimestamp(){
        return Long.toString(System.currentTimeMillis()/1000);
    }
    private Map<String, String>getThirdEmployeeMap(String companyNo){
        Map<String,String>map=new HashMap<String, String>();
        List<ThirdEmployee>thirdEmployeeList=jdbcSession.findArray(ThirdEmployee.class).eq("companyNo",companyNo).exe();
        thirdEmployeeList.forEach(item->{
            map.put(item.getThirdId(),item.getKhtId());
        });
        return map;
    }
    private Map<String,ThirdDepartment> getThirdDepartmentMap(){
        Map<String,ThirdDepartment>thirdDepartmentMap=new HashMap<>();
        List<ThirdDepartment>thirdDepartmentList=jdbcSession.findArray(ThirdDepartment.class).exe();
        thirdDepartmentList.forEach(item->{
            thirdDepartmentMap.put(item.getThirdId(),item);
        });
        return  thirdDepartmentMap;
    }
}
